package huffman;

import java.io.*;

public class bit_reader {

	FileInputStream input;
	int current, plus1, plus2;
	int count;
	boolean finished;

	public bit_reader(String file) throws Exception {
		this(new File(file));
	}

	public bit_reader(File file) throws Exception {
		file.createNewFile();
		if (!file.canRead())
			throw new IOException("can not open" + file);
		input = new FileInputStream(file);
		plus1 = input.read();
		plus2 = input.read();
	}
	
	public bit_reader(FileInputStream fis) throws Exception{
		this.input=fis;
		plus1 = input.read();
		plus2 = input.read();
	}
	
	public boolean next() throws Exception {
		if (!hasNext())
			throw new Exception();
		if (count == 0) {
			current = plus1;
			plus1 = plus2;
			plus2 = input.read();
			count = 8;
			if (plus2 < 0) {
				finished = true;
				count = 8 - plus1;
			}
		}
		--count;
		int bit = current & 0x80;
		bit = bit >> 7;
		current = current << 1;
		if (bit == 0)
			return false;
		return true;
	}

	public boolean hasNext() {
		return !(finished && count == 0);
	}

	public static void main(String[] args) throws Exception {
		bit_reader br = new bit_reader("F:\\test\\test.txt.huf\\comp");
		while (br.hasNext()) {
			if (br.next())
				System.out.print("1");
			else
				System.out.print("0");
		}
	}
}
